<?php

/**
 *
 * @name My
 * @author Roman Metlinskyi <r.metlinskyi@gmail.com>
 * @version 0.05
 * @license Apache License 2.0
 * @copyright All right reserved.
 * autoloader
 */

class My
{
  // static instance
  private static $_my;

  protected $namespace;
  protected $dirname;

  private function __construct()
  {
    $this->__init(__FILE__,__CLASS__);
  }

  private function __clone()
  {
    //singleton protected
  }

  protected function __init($file = __FILE__, $class = __CLASS__)
  {
    $this->dirname = dirname($file) . DIRECTORY_SEPARATOR;
    $this->namespace = $this->dirname . $class . DIRECTORY_SEPARATOR;
  }

  protected function __preload($class = __CLASS__)
  {
    foreach (glob("{$this->namespace}*.php") as $filename) {
      require_once $filename;
    }
  }


   /*
   * Get My instance
   */

  public static function My()
  {
    if(!isset(self::$_my)){
        self::$_my = new self();
    }

    return self::$_my;
  }

  public function Init()
  {
    $this->__init(__FILE__,__CLASS__);
  }

  /*
   * Import namespace require __CLASS__/<$name>.php file
   */

  public function Using($name)
  {
    require_once ( "{$this->namespace}{$name}.php");
  }

  public function Create($name, $arguments = null)
  {
    if (!class_exists($name))
        $this->Using($name);

    // Get singleton instance
    if (method_exists($name, $name)){
      return $name::$name();
    }

    // Create new instance
    return ($arguments != null)
        ? new $name(implode(',',$arguments))
        : new $name();

    throw new Exception("{$name} class not found");
  }

 /*
  * Get namespace
  */

  public static function __callStatic($name, $arguments)
  {;
    // Create new instance
    return My::My()->Create($name, $arguments);
  }

  public function __call($name, $arguments)
  {
    if (!method_exists($this, $name)) {
       // Create new instance

      return $this->Create($name, $arguments);
    }
  }

 /*
  * Property access
  */

  public function __get($name)
  {
    $methodName = "get{$name}";
    if (method_exists($this, $methodName)) {
      return $this->$methodName();
    }

    // Create new instance
    return $this->Create($name);
  }


  /*
   * @region: Properties
   */

  /*
   *  Current directory
   */
  public function getDirectory()
  {
    return $this->dirname;
  }

  /*
   *  Current vrsion
   */
  public function getVersion()
  {
    return self::System()->Type(__CLASS__)->Attributes('version');
  }

  public function getCopyright()
  {
    return self::System()->Type(__CLASS__)->Attributes('copyright');
  }

  public function getLicense()
  {
    return self::System()->Type(__CLASS__)->Attributes('license');
  }
}

function my(){
    return My::My();
}